package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminMapper;
import com.heima.admin.service.AdminService;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdminDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.hbase.thirdparty.com.google.common.base.Objects;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdUser> implements AdminService {
    @Override
    public ResponseResult login(AdminDto adminDto) {
//        参数校验
        if (adminDto == null ||
                StringUtils.isBlank(adminDto.getName())
                || StringUtils.isBlank(adminDto.getPassword())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
//        1、根据用户名查询用户信息
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adminDto.getName()));
//        2、用户信息校验
//        用户是否存在
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//       密码是否正确
        String inpwd= MD5Utils.encode(adminDto.getPassword()+user.getSalt());
        if (!Objects.equal(inpwd,user.getPassword())){
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        生成token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
//        3、封装token和用户信息并返回
        Map<String,Object>map=new HashMap<>();
        map.put("user",user);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
